<script>
import wechatPayIcon from "./wechatPay.svg"
import personIcon from "./person.svg"
import cloudIcon from "./cloud.svg"
import { getShowImage, showModal } from "@/utils"
import groupIcon from "./group.svg"
import avatar from "@/components/avatar.vue"
import closeIcon from "./close.svg"
import unhappyIcon from "./unhappy.svg"
import request from "@/utils/request"
import numberUtils from "@/utils/numberUtils"
import pay from "@/utils/pay"
import dateUtils from "@/utils/dateUtils"
import refreshIcon from "./refresh.svg"
import teamInfo from "./components/teamInfo.vue"

let countDownTimer = null //拼团倒计时计时器
export default {
  name: "teamBuying",
  computed: {
    numberUtils() {
      return numberUtils
    },
    //拼团剩余时间，将接口返回的秒单位的时间转换为 时分秒
    teamBuyingRemainTime() {
      return dateUtils.formatTimeObject2(this.groupRemainingTime)
    },
    //截断的头像列表，头像列表长度超过2个时只展示前面两个，没超过时原样返回
    truncatedAvatarList() {
      if (this.myTeamBuyingDetails && this.myTeamBuyingDetails.groupBuyUsers) {
        return this.myTeamBuyingDetails.groupBuyUsers.slice(0, 2)
      }
      return []
    },
  },
  data() {
    return {
      wechatPayIcon,
      personIcon,
      cloudIcon,
      groupIcon,
      closeIcon,
      unhappyIcon,
      refreshIcon,
      // 当前选择的拼团信息
      currentSelectGroupBuyInfo: {
        groupBuyId: "",
        price: 0,
        personNum: 0,
      },
      errorMessageList: [],
      groupRemainingTime: 0,
      createdGroupBuyingPromise: {
        resolve: null,
        reject: null,
      },
      joinTeamBuyingPromise: {
        resolve: null,
        reject: null,
      },
      shareUserTeamBuyingDetails: null, //分享人的拼团详情
    }
  },
  components: { avatar, teamInfo },
  props: {
    commodityName: String,
    commodityIcon: String,
    commodityId: String,
    commodityType: Number, // 商品类型，1 课程
    teamBuyingDetails: Array, // 商品拼团配置
    myTeamBuyingDetails: Object, // 我的拼团详情
    groupBuyId: String, // 我的拼团id
    groupIdentification: String, // 我的拼团标识
    shareUserGroupIdentification: String, // 分享人的拼团标识（加入别人的拼团时需要用到）
    shareUserGroupBuyId: String, // 分享人的拼团id
  },
  methods: {
    async init() {
      //获取商品配置的拼团配置
      request({
        url: "commodityGroupBuy/getCommodityGroupBuys",
        data: {
          commodityType: this.commodityType,
          commodityId: this.commodityId,
        },
        showLoading: true,
      })
        .then((data) => {
          this.$emit("update:teamBuyingDetails", data)
          //默认选中第一个
          if (data && data.length) {
            this.currentSelectGroupBuyInfo = data[0]
          }
        })
        .catch((err) => {
          console.log(err, "err")
        })
      //获取我的拼团详情
      await this.getMyGroupBuyId()
      if (this.groupBuyId && this.groupIdentification) {
        await this.getMyTeamBuyingDetails()
        //弹出拼团详情
        if (this.myTeamBuyingDetails) {
          this.$nextTick(() => {
            this.checkTeamBuyingProgress()
          })
        }
        this.checkIfGroupSuccess()
      }
    },
    getShowImage,
    // 发起拼团
    chooseTeamMemberCount() {
      return new Promise((resolve, reject) => {
        this.$refs["choose-team-member-count"].open()
        this.createdGroupBuyingPromise.resolve = resolve
        this.createdGroupBuyingPromise.reject = reject
      })
    },
    // 查看拼团进度
    checkTeamBuyingProgress() {
      this.$refs["my-team-process-prop"].open()
    },
    //发起拼团
    createGroup() {
      request({
        url: "commodityGroupBuy/launchGroup",
        data: {
          groupBuyId: this.currentSelectGroupBuyInfo.groupBuyId,
        },
        errorHandle: true,
        showLoading: true,
      })
        .then((data) => {
          //拉取支付
          pay
            .handlePay(data)
            .then(async () => {
              //关闭选择成团人数弹窗
              this.$refs["choose-team-member-count"].close()
              //重新获取拼团信息
              await this.getMyGroupBuyId()
              await this.getMyTeamBuyingDetails()
              //弹出拼团进度
              this.checkTeamBuyingProgress()
              this.createdGroupBuyingPromise.resolve()
            })
            .catch((err) => {
              this.createdGroupBuyingPromise.reject()
            })
        })
        .catch((err) => {
          this.createdGroupBuyingPromise.reject()
        })
    },
    //加入别人的团
    joinGroup() {
      return new Promise((resolve, reject) => {
        request({
          url: "commodityGroupBuy/joinGroup",
          data: {
            groupIdentification: this.shareUserGroupIdentification,
          },
          showLoading: true,
        })
          .then((data) => {
            //拉取支付
            pay
              .handlePay(data)
              .then(async () => {
                //重新获取拼团信息
                await this.getMyGroupBuyId()
                if (this.groupBuyId && this.groupIdentification) {
                  await this.getMyTeamBuyingDetails()
                  //弹出拼团进度
                  this.checkTeamBuyingProgress()
                  this.checkIfGroupSuccess()
                } else {
                  await showModal({
                    title: "提示",
                    content: "订单正在处理中，如有问题请联系客服",
                    showCancel: false,
                  })
                }
                resolve()
              })
              .catch((err) => {
                console.log(err, "err")
                showModal({
                  title: "提示",
                  content: err,
                })
                reject()
              })
          })
          .catch(async (err) => {
            console.log(err, "err")
            this.errorMessageList = ["抱歉，" + err, "可自行发起或参与其他拼团哦~"]
            this.$emit("update:shareUserGroupIdentification", "")
            this.$refs["error-popup"].open()
            //获取用户自己加入的拼团
            // await this.getMyGroupBuyId()
            // await this.getMyTeamBuyingDetails()
            reject()
          })
      })
    },
    // 获取我加入的拼团id
    getMyGroupBuyId() {
      return new Promise((resolve, reject) => {
        request({
          url: "commodityGroupBuy/getGroupBuyRecordsUser",
          data: {
            commodityType: this.commodityType,
            commodityId: this.commodityId,
          },
          showLoading: true,
          errorHandle: true,
        }).then((data) => {
          if (data && data.groupBuyId && data.groupIdentification) {
            this.$emit("update:groupBuyId", data.groupBuyId)
            this.$emit("update:groupIdentification", data.groupIdentification)
          } else {
            this.$emit("update:groupBuyId", "")
            this.$emit("update:groupIdentification", "")
          }
          resolve()
        })
      })
    },
    // 获取我的拼团详情
    getMyTeamBuyingDetails() {
      return new Promise((resolve, reject) => {
        //用户当前没有拼团
        if (!this.groupBuyId || !this.groupIdentification) {
          this.$emit("update:myTeamBuyingDetails", null)
          this.$nextTick(() => {
            this.$refs["my-team-process-prop"].close()
          })
          resolve()
          return
        }
        request({
          url: "commodityGroupBuy/groupBuyDetails",
          data: {
            groupBuyId: this.groupBuyId,
            groupIdentification: this.groupIdentification,
          },
          showLoading: true,
          errorHandle: true,
        }).then(async (data) => {
          this.$emit("update:myTeamBuyingDetails", data)
          let that = this
          function handleGroupExpiredError() {
            that.$emit("update:myTeamBuyingDetails", null)
            that.$emit("update:groupBuyId", "")
            that.$emit("update:groupIdentification", "")
            that.$refs["my-team-process-prop"].close()
            // that.refreshTeamBuyingProcess()
          }
          // 确保用户已经付款已经入团
          if (data.isPay === 1 && data.isJoin) {
            //检查拼团是否已经拼成
            if (data.lackNum === 0) {
              //已经拼成
              resolve()
              return
            }
            // 检查拼团是否已过期
            if (!data.remainingTime || data.remainingTime <= 0) {
              handleGroupExpiredError()
              reject()
              return
            }
            this.groupRemainingTime = data.remainingTime
            //启用倒计时计时器
            if (countDownTimer) {
              clearInterval(countDownTimer)
            }
            countDownTimer = setInterval(() => {
              this.groupRemainingTime--
              if (this.groupRemainingTime <= 0) {
                clearInterval(countDownTimer)
                handleGroupExpiredError()
                that.errorMessageList = ["抱歉，拼团已过期", "请重新发起拼团"]
                that.$refs["error-popup"].open()
              }
            }, 1000)
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    //获取被分享人的拼团详情
    getShareUserTeamBuyingDetails() {
      return new Promise((resolve, reject) => {
        request({
          url: "commodityGroupBuy/groupBuyDetails",
          data: {
            groupBuyId: this.shareUserGroupBuyId,
            groupIdentification: this.shareUserGroupIdentification,
          },
          showLoading: true,
          errorHandle: true,
        })
          .then(async (data) => {
            let that = this
            function handleGroupExpiredError(message) {
              that.shareUserTeamBuyingDetails = null
              that.$emit("update:shareUserGroupIdentification", "")
              that.$emit("update:shareUserGroupBuyId", "")
              that.errorMessageList = ["抱歉，" + message, "可自行发起或参与其他拼团哦~"]
              that.$refs["error-popup"].open()
              reject()
            }
            //检查拼团是否已经拼成
            if (data.lackNum === 0) {
              handleGroupExpiredError("该拼团人数已满")
              return
            }
            // 检查拼团是否已过期
            if (!data.remainingTime || data.remainingTime <= 0) {
              handleGroupExpiredError("该拼团已成团")
            }
            this.shareUserTeamBuyingDetails = data
            resolve()
          })
          .catch((err) => {
            reject()
          })
      })
    },
    //刷新拼团进度
    async refreshTeamBuyingProcess() {
      await this.getMyGroupBuyId()
      await this.getMyTeamBuyingDetails()
      this.checkIfGroupSuccess()
    },
    //检查是否已经拼成
    checkIfGroupSuccess() {
      if (this.myTeamBuyingDetails && this.myTeamBuyingDetails.lackNum === 0) {
        this.$refs["my-team-process-prop"].close()
        showModal({
          title: "提示",
          content: "拼团成功",
          showCancel: false,
        })
        this.$emit("refreshDetail")
      }
    },
    //查看邀请人分享的拼团信息
    viewTeamInfo() {
      return new Promise((resolve, reject) => {
        this.getShareUserTeamBuyingDetails()
          .then(() => {
            this.$refs["team-info"].open()
          })
          .catch(() => {
            reject()
            return
          })
        this.joinTeamBuyingPromise.resolve = resolve
        this.joinTeamBuyingPromise.reject = reject
      })
    },
  },
  emits: [
    "update:teamBuyingDetails",
    "update:myTeamBuyingDetails",
    "update:groupBuyId",
    "update:groupIdentification",
    "refreshDetail",
    "update:shareUserGroupIdentification",
  ],
  beforeDestroy() {
    //销毁计时器
    if (countDownTimer) {
      clearInterval(countDownTimer)
      countDownTimer = null
    }
  },
}
</script>

<template>
  <view class="page">
    <!--		选择成团人数-->
    <uni-popup ref="choose-team-member-count" type="bottom" :safe-area="false">
      <view class="choose-team-member-count-popup popup-content">
        <view class="popup-header">
          <view
            class="close-btn"
            @click="
              () => {
                $refs['choose-team-member-count'].close()
                createdGroupBuyingPromise.reject()
              }
            "
            >取消</view
          >
          <view class="primary-btn" @click="createGroup">立即购买</view>
        </view>

        <view class="content">
          <!--				拼团说明-->
          <view class="info">
            <view class="title">拼团说明</view>
            <view class="content">
              <image class="icon" :src="wechatPayIcon"></image>
              <text class="text">提交订单.....</text>
              <image class="icon" :src="personIcon"></image>
              <text class="text">邀请好友加入冲刺班.....</text>
              <image class="icon" :src="cloudIcon"></image>
              <text class="text">拼团成功</text>
            </view>
          </view>
          <!--					商品信息-->
          <view class="product-info">
            <image class="product-icon" :src="getShowImage(commodityIcon)" mode="aspectFill"></image>
            <view class="product-text">
              <view class="team-price">{{ `￥${numberUtils.fenToYuan(currentSelectGroupBuyInfo.price)}` }}</view>
              <view class="product-name">{{ commodityName }}</view>
              <view class="team-member-count">{{ `已选：${currentSelectGroupBuyInfo.personNum}人团` }}</view>
            </view>
          </view>
          <!--					成团人数-->
          <view class="team-member-count-list block">
            <view class="title">成团人数</view>
            <view class="list">
              <view
                class="item"
                v-for="item in teamBuyingDetails"
                :key="item.groupBuyId"
                :class="{ active: currentSelectGroupBuyInfo.groupBuyId === item.groupBuyId }"
                @click="() => (currentSelectGroupBuyInfo = item)"
              >
                <view class="text">{{ `￥${numberUtils.fenToYuan(item.price)}` }}</view>
                <view class="text">{{ `${item.personNum}人团` }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
    <!--		查看拼团进度弹窗-->
    <uni-popup ref="my-team-process-prop" type="center" :is-mask-click="false">
      <view class="my-team-process-prop popup-content" v-if="myTeamBuyingDetails">
        <image class="close-icon" :src="closeIcon" @click.stop="() => $refs['my-team-process-prop'].close()"></image>

        <view class="my-team-process-prop-header d-flex justify-center align-center">
          <view class="text">拼团剩余时间</view>
          <view class="number">{{ numberUtils.padZero(teamBuyingRemainTime.h) }}</view>
          <view class="text">:</view>
          <view class="number">{{ numberUtils.padZero(teamBuyingRemainTime.m) }}</view>
          <view class="text">:</view>
          <view class="number">{{ numberUtils.padZero(teamBuyingRemainTime.s) }}</view>
        </view>

        <view class="content">
          <!--				我的拼团进度-->
          <view class="team-process">
            <view class="d-flex align-center justify-between title">
              <view class="left">
                <image class="icon" :src="groupIcon"></image>
                我的拼团进度
              </view>
              <!--							刷新按钮-->
              <view class="refresh-btn d-flex align-center" @click="refreshTeamBuyingProcess">
                <image :src="refreshIcon" style="width: 30rpx; height: 30rpx; margin-right: 10rpx"></image>
                刷新
              </view>
            </view>

            <view class="d-flex flex-column align-center">
              <!--							当前拼团人数-->
              <view class="status-text">
                <text>当前</text>
                <text class="number">{{ myTeamBuyingDetails.commodityGroupBuy.personNum - myTeamBuyingDetails.lackNum }}</text>
                <text>人，再邀</text>
                <text class="number">{{ myTeamBuyingDetails.lackNum }}</text>
                <text>人即可拼团成功</text>
              </view>
              <!--							拼团用户头像列表-->
              <view class="avatar-list d-flex">
                <block v-for="item in truncatedAvatarList" :key="item.userId">
                  <view class="avatar-item" :class="{ 'team-leader': item.isLeader === 1 }">
                    <avatar width="100rpx" height="100rpx" :nick-name-prop="item.userId" :user-icon-prop="item.userIcon"></avatar>
                  </view>
                </block>
                <!--								空位占位-->
                <view class="avatar-item placeholder"></view>
                <view class="avatar-item placeholder" v-if="myTeamBuyingDetails.lackNum > 1"></view>
              </view>
              <view class="tips">*若拼团不成功，所支付金额全部返还</view>
              <button open-type="share" class="share-btn">邀请好友参与拼团</button>
            </view>

            <!--						团总人数和价格-->
            <view class="team-info">
              <text>{{ myTeamBuyingDetails.commodityGroupBuy.personNum }}人团，拼团价格</text>
              <text class="number">￥{{ numberUtils.fenToYuan(myTeamBuyingDetails.commodityGroupBuy.price) }}</text>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 错误弹窗，当用户试图加入一个人数已满、已过期的团；拼团超时 时弹出 -->
    <uni-popup ref="error-popup" type="center" @change="(val) => !val.show && $refs['my-team-process-prop'].close()">
      <view class="team-full-popup d-flex justify-center align-center flex-column">
        <image :src="unhappyIcon" class="error-icon"></image>
        <view style="margin-top: 30rpx">
          <view class="message" v-for="item in errorMessageList" :key="item">{{ item }}</view>
        </view>
        <view class="confirm-btn d-flex align-center justify-center" @click="() => $refs['error-popup'].close()">确定</view>
      </view>
    </uni-popup>

    <!--		被邀请的人加团的时候查看团信息-->
    <teamInfo
      ref="team-info"
      @takeOrder="() => joinTeamBuyingPromise.resolve()"
      @close="() => joinTeamBuyingPromise.reject()"
      :commodity-icon="commodityIcon"
      :teamInfo="shareUserTeamBuyingDetails"
    ></teamInfo>
  </view>
</template>

<style scoped lang="scss">
.page {
  .choose-team-member-count-popup {
    border-radius: 30rpx 30rpx 0 0;
    padding-bottom: env(safe-area-inset-bottom);
    overflow: hidden;
    > .content {
      > .info {
        color: #63676b;
        .title {
          font-size: 32rpx;
        }
        .content {
          margin-top: 4rpx;
          display: flex;
          align-items: center;
          font-size: 30rpx;
          .icon {
            width: 30rpx;
            height: 30rpx;
            margin: 0 3rpx;
          }
          .text {
            width: max-content;
          }
        }
      }
      > .product-info {
        margin-top: 30rpx;
        display: flex;
        align-items: center;
        .product-icon {
          width: 272rpx;
          height: 200rpx;
        }
        .product-text {
          margin-left: 20rpx;
          width: 0;
          flex: 1;
          .team-price {
            font-size: 40rpx;
            color: #e83030;
            font-weight: bold;
          }
          .product-name {
            margin-top: 4rpx;
            font-size: 32rpx;
            width: 100%;
            //文本溢出部分自动换行
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .team-member-count {
            margin-top: 20rpx;
            color: #63676b;
            font-size: 30rpx;
          }
        }
      }
      > .team-member-count-list {
        margin-top: 30rpx;
        .list {
          display: flex;
          width: 100%;
          overflow-x: auto;
          .item {
            border-radius: 20rpx;
            border: 2rpx solid rgba(99, 103, 107, 1);
            width: 180rpx;
            height: 108rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            font-size: 30rpx;
            &:not(:last-child) {
              margin-right: 30rpx;
            }
            &.active {
              color: #e83030;
              border: 2rpx solid #e83030;
            }
          }
        }
      }
    }
  }
  .my-team-process-prop {
    border-radius: 30rpx;
    width: 90vw;
    position: relative;
    > .my-team-process-prop-header {
      background: #ffe6da;
      padding: 20rpx 0;
      border-radius: 30rpx 30rpx 0 0;
      font-size: 32rpx;
      .text {
        margin: 0 10rpx;
      }
      .number {
        background: white;
        padding: 6rpx 10rpx;
        border-radius: 10rpx;
        color: #e83030;
      }
    }
    .close-icon {
      width: 80rpx;
      height: 80rpx;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      bottom: -120rpx;
      z-index: 9999;
    }
    .team-process {
      .title {
        margin-bottom: 30rpx;
        .left {
          font-size: 36rpx;
          display: flex;
          align-items: center;
          .icon {
            width: 40rpx;
            height: 40rpx;
            margin-right: 10rpx;
          }
        }
        .refresh-btn {
          color: var(--text-color-light);
          font-size: 32rpx;
        }
      }
      .status-text {
        font-size: 32rpx;
        .number {
          color: #e83030;
        }
      }
      .avatar-list {
        margin-top: 20rpx;
        padding-bottom: 30rpx;
        .avatar-item {
          width: 100rpx;
          height: 100rpx;
          border-radius: 50%;
          &:not(:last-child) {
            margin-right: 20rpx;
          }
          &.placeholder {
            border: 2rpx solid rgba(187, 187, 187, 1);
            display: flex;
            align-items: center;
            justify-content: center;
          }
          &.placeholder::after {
            content: "?";
            font-size: 50rpx;
            color: rgba(187, 187, 187, 1);
          }
          &.team-leader {
            position: relative;
          }
          &.team-leader::after {
            position: absolute;
            width: 90rpx;
            height: 40rpx;
            border-radius: 20rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 30rpx;
            color: white;
            content: "团长";
            background: #f2a249;
            bottom: -20rpx;
            left: 50%;
            transform: translateX(-50%);
            z-index: 999;
          }
        }
      }
      .tips {
        margin-top: 50rpx;
        color: #63676b;
        font-size: 30rpx;
      }
      .share-btn {
        margin-top: 20rpx;
        background: #f06220;
        color: white;
        font-size: 32rpx;
        padding: 0 60rpx;
        border-radius: 41rpx;
      }
      .team-info {
        margin-top: 32rpx;
        color: #63676b;
        font-size: 30rpx;
        .number {
          color: #e83030;
        }
      }
    }
  }
  .team-full-popup {
    background: var(--background-color);
    border-radius: 30rpx;
    width: 550rpx;
    padding: 40rpx;
    .error-icon {
      width: 100rpx;
      height: 100rpx;
    }
    .message {
      font-size: 32rpx;
      //文本溢出自动换行
      word-wrap: break-word;
      overflow-wrap: break-word;
      text-align: center;
      line-height: 1.7;
    }
    .confirm-btn {
      margin-top: 40rpx;
      width: 200rpx;
      height: 60rpx;
      border-radius: 30rpx;
      font-size: 30rpx;
      color: white;
      background: #5cb683;
    }
  }
  .popup-content {
    background: var(--background-color);
    > .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #eeeeee;
      padding: 20rpx 30rpx;
      .close-btn {
        font-size: 32rpx;
      }
      .primary-btn {
        background: #f06220;
        color: white;
        font-size: 32rpx;
        padding: 10rpx 40rpx;
        border-radius: 31rpx;
      }
    }
    > .content {
      padding: 20rpx 30rpx;
      > .block {
        .title {
          font-size: 36rpx;
          display: flex;
          align-items: center;
          margin-bottom: 30rpx;
          .icon {
            width: 40rpx;
            height: 40rpx;
            margin-right: 10rpx;
          }
        }
      }
    }
  }
}
</style>
